﻿Imports System.ComponentModel

Partial Public Class IncomeWindow
    Public WithEvents oWindowList As OpenedWindowList = OpenedWindowList.GetList()
    Private WithEvents oWindow As OpenedWindowClass
    Public WithEvents incomesList As IncomeList = IncomeList.GetList()
    Private WithEvents IncomeTrans As IncomeClass

    Dim IncomeDB As New IETrackerDataClassesDataContext
    Dim frmIsDirty As Boolean = False
    Private _pageIsValid As Boolean = True
    Dim editFlag As Integer
    Dim al As New ArrayList
    Dim comboClassTextbox As New TextBox

#Region "Window Events"

    Private Sub IncomeWindow_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles IncomeWindow.Closing
        If frmIsDirty Then
            If MessageBox.Show("There are unsaved entries. Do you really want to exit?", "Exit", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.No Then
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub IncomeWindow_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Dim ied As IEnumerable(Of OpenedWindowClass) = From d In oWindowList Where d.WindowID = Me.Name
        oWindowList.Remove(ied.First)

        If Application.Current.Windows.Count = 1 Then
            Application.Current.Windows(0).Activate()
        End If
    End Sub

    Private Sub IncomeWindow_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        comboClassTextbox = TryCast(ComboBoxIncomeType.Template.FindName("PART_EditableTextBox", ComboBoxIncomeType), TextBox)
        AddHandler comboClassTextbox.TextChanged, AddressOf ComboBox_TextChanged

        LoadIncomeTypes()
        noSelectedData()
        HookupChangeEventHandlers()
        LoadSubHeader()
    End Sub
#End Region

#Region "RibbonButton Click events"

    Private Sub RibbonButtonCancel_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonCancel.Click
        If editFlag = HelperClass.EditMode.Add Then
            HelperClass.ClearTextBox(GridIncome)
            HelperClass.ClearComboBox(GridIncome)
            DatePickerTransactionDate.SelectedDate = Nothing
            noSelectedData()
        ElseIf editFlag = HelperClass.EditMode.Edit Then

            If listBoxIncome.SelectedIndex >= 0 Then
                With listBoxIncome.SelectedItem
                    ComboBoxIncomeType.SelectedValue = .Incometypeid
                    DatePickerTransactionDate.SelectedDate = .Incomedate
                    TextBoxAmount.Text = .IncomeAmount
                    CheckBoxOneOff.IsChecked = .Incomeoneoff
                    TextBoxComment.Text = .Incomecomment
                End With

            End If
            frmIsDirty = True
            setButtonProperties()
        End If
    End Sub


    Private Sub RibbonButtonDelete_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonDelete.Click
        Dim index As Integer = listBoxIncome.SelectedIndex
        If index >= 0 Then
            Try
                Dim warningString As String = "Do you really want to delete this transaction?" & ControlChars.Lf & ControlChars.Lf & listBoxIncome.SelectedItem.Incometype & " - " & listBoxIncome.SelectedItem.Incomedate
                If System.Windows.MessageBox.Show(warningString, "Delete Transaction", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    Dim selectedIncomeTransactionID As Integer = listBoxIncome.SelectedValue.Incomeid
                    
                    Dim deleteFromTransaction = From trans In IncomeDB.Transactions _
                                                Where trans.TransactionID = selectedIncomeTransactionID
                    IncomeDB.Transactions.DeleteOnSubmit(deleteFromTransaction.First)
                    IncomeDB.SubmitChanges()

                    Dim IncomeClass As IEnumerable(Of IncomeClass) = From d In incomesList Where d.IncomeId = selectedIncomeTransactionID
                    incomesList.Remove(IncomeClass.First)

                    HelperClass.ClearTextBox(GridIncome)
                    HelperClass.ClearComboBox(GridIncome)
                    DatePickerTransactionDate.SelectedDate = Nothing
                    noSelectedData()
                End If

            Catch ex As Exception
                MessageBox.Show("Error encountered while deleting the record." & ControlChars.Lf & ControlChars.Lf & ex.message.tostring, "Delete Error", MessageBoxButton.OK, MessageBoxImage.Error)
            End Try
        End If
    End Sub

    Private Sub RibbonButtonNew_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonNew.Click
        mainOverlay.Visibility = Visibility.Collapsed
        editFlag = HelperClass.EditMode.Add
        ComboBoxIncomeType.IsEnabled = True

        listBoxIncome.SelectedIndex = -1
        HelperClass.ClearTextBox(GridIncome)
        HelperClass.ClearComboBox(GridIncome)
        DatePickerTransactionDate.SelectedDate = Nothing

        frmIsDirty = True
        setButtonProperties()
    End Sub


    Private Sub RibbonButtonSave_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonSave.Click
        pageIsValid(DatePickerTransactionDate.Name, EntryValidation.ValidateDatePicker(DatePickerTransactionDate))
        pageIsValid(ComboBoxIncomeType.Name, EntryValidation.ValidateEditableCombo(ComboBoxIncomeType, comboClassTextbox))
        pageIsValid(TextBoxAmount.Name, EntryValidation.ValidateText(TextBoxAmount))

        If _pageIsValid Then
            Try
                Dim transactionTypeID As Integer = ComboBoxIncomeType.SelectedValue
                If editFlag = HelperClass.EditMode.Add Then
                    Dim saveNewTransaction As New Transaction
                    If transactionTypeID = 0 Then
                        Dim saveNewTransactionDescription As New TransactionDescription
                        With saveNewTransactionDescription
                            .TransactionDescription = ComboBoxIncomeType.Text
                            .IsAutoDeduct = False
                        End With
                        IncomeDB.TransactionDescriptions.InsertOnSubmit(saveNewTransactionDescription)
                        IncomeDB.SubmitChanges()

                        Dim saveNewTransactionType As New TransactionType
                        With saveNewTransactionType
                            .TransactionTypeDescID = 1
                            .TransactionDescID = saveNewTransactionDescription.TransactionDescriptionID
                            .OneOff = CheckBoxOneOff.IsChecked
                        End With
                        IncomeDB.TransactionTypes.InsertOnSubmit(saveNewTransactionType)
                        IncomeDB.SubmitChanges()

                        transactionTypeID = saveNewTransactionType.TransactionTypeID
                    End If

                    With saveNewTransaction
                        .TransactionAmount = TextBoxAmount.Text
                        .TransactionDate = DatePickerTransactionDate.Text
                        .TransactionTypeID = transactionTypeID
                        .Comment = TextBoxComment.Text
                    End With
                    IncomeDB.Transactions.InsertOnSubmit(saveNewTransaction)
                    IncomeDB.SubmitChanges()


                    IncomeTrans = New IncomeClass(ComboBoxIncomeType.Text, TextBoxAmount.Text, DatePickerTransactionDate.Text, saveNewTransaction.TransactionID, transactionTypeID, CheckBoxOneOff.IsChecked, TextBoxComment.Text)
                    incomesList.Add(IncomeTrans)
                    sortData()

                ElseIf editFlag = HelperClass.EditMode.Edit Then
                    Dim selectedIncomeItem As Integer = listBoxIncome.SelectedValue.Incomeid

                    Dim Income = From trans In IncomeDB.Transactions _
                          Join transType In IncomeDB.TransactionTypes _
                          On trans.TransactionTypeID Equals transType.TransactionTypeID _
                          Where trans.TransactionID = selectedIncomeItem

                    With Income.First
                        .trans.TransactionDate = DatePickerTransactionDate.Text
                        .trans.TransactionAmount = TextBoxAmount.Text
                        .trans.Comment = TextBoxComment.Text
                        .transType.OneOff = CheckBoxOneOff.IsChecked
                    End With
                    IncomeDB.SubmitChanges()

                    'reflect changes in list
                    With incomesList.Where(Function(x) x.IncomeId = selectedIncomeItem).First
                        .IncomeAmount = TextBoxAmount.Text
                        .IncomeDate = DatePickerTransactionDate.Text
                        .IncomeOneOff = CheckBoxOneOff.IsChecked
                        .IncomeComment = TextBoxComment.Text
                    End With
                End If
                frmIsDirty = False
                setButtonProperties()
            Catch ex As Exception
                MessageBox.Show("Error encountered while saving the record." & ControlChars.Lf & ControlChars.Lf & ex.message.tostring, "Save Error", MessageBoxButton.OK, MessageBoxImage.Error)

            End Try
        End If
    End Sub
#End Region

#Region "Support Procedures"
    Public Function FilterCompletedTasks(ByVal t As Object) As Boolean
        Dim _tasks As New IncomeClass
        _tasks = t
        Return _tasks.IncomeType.ToUpper.Contains(searchBox.Text.ToUpper)
    End Function

    Sub sortData()
        Dim iIncome As IEnumerable(Of IncomeClass) = From d In incomesList Order By d.IncomeDate Descending
        For Each i In iIncome
            incomesList.Remove(i)
            incomesList.Add(i)
        Next
    End Sub

    Private Sub HookupChangeEventHandlers()
        For Each IncomeTrans As IncomeClass In incomesList
            HookupChangeEventHandler(IncomeTrans)
        Next
    End Sub

    Private Sub HookupChangeEventHandler(ByVal IncomeTrans As IncomeClass)
        AddHandler IncomeTrans.PropertyChanged, _
          AddressOf HandlePropertyChanged
    End Sub

    Private Sub HandlePropertyChanged( _
    ByVal sender As Object, _
    ByVal e As PropertyChangedEventArgs)

        Dim propName As String = e.PropertyName
        Dim myIncome As IncomeClass = CType(sender, IncomeClass)

        Dim propInfo As System.Reflection.PropertyInfo = _
          GetType(IncomeClass).GetProperty(propName)
        Dim value As Object = _
          propInfo.GetValue(myIncome, Nothing)

    End Sub

#End Region

#Region "Control Events"
    Private Sub searchBox_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles searchBox.TextChanged
        If Not listBoxIncome Is Nothing Then
            Dim icview As ICollectionView = CollectionViewSource.GetDefaultView(incomesList)
            'If icview.Filter Is Nothing Then
            icview.Filter = New Predicate(Of Object)(AddressOf FilterCompletedTasks)
            'Else
            'icview.Filter = Nothing
            'End If
        End If
    End Sub

    Private Sub searchBox_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles searchBox.GotFocus
        If searchBox.Text = "Search" Then
            searchBox.Text = Nothing
        End If
    End Sub

    Private Sub listBoxIncome_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles listBoxIncome.SelectionChanged
        If listBoxIncome.SelectedIndex >= 0 Then
            With listBoxIncome.SelectedValue
                DatePickerTransactionDate.SelectedDate = .IncomeDate
                ComboBoxIncomeType.SelectedValue = .IncomeTypeId
                TextBoxAmount.Text = .IncomeAmount
                CheckBoxOneOff.IsChecked = .Incomeoneoff
                TextBoxComment.Text = .IncomeComment
            End With

            mainOverlay.Visibility = Visibility.Collapsed
            editFlag = HelperClass.EditMode.Edit
            frmIsDirty = True
            setButtonProperties()
        Else
            HelperClass.ClearTextBox(GridIncome)
            HelperClass.ClearComboBox(GridIncome)
            DatePickerTransactionDate.SelectedDate = Nothing
        End If

    End Sub


    Private Sub CheckBoxOneOff_Unchecked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles CheckBoxOneOff.Unchecked, CheckBoxOneOff.Checked
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub ComboBox_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
        Me.Title = ComboBoxIncomeType.Text & IIf(Not frmIsDirty, " (unsaved)", "")
        For itemIndex = 0 To oWindowList.Count - 1
            If oWindowList(itemIndex).WindowID = Me.Name Then
                oWindowList(itemIndex).WindowName = Me.Title
            End If
        Next
        pageIsValid(ComboBoxIncomeType.Name, EntryValidation.ValidateEditableCombo(ComboBoxIncomeType, comboClassTextbox))
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub TextBoxAmount_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBoxAmount.TextChanged
        pageIsValid(TextBoxAmount.Name, EntryValidation.ValidateIsNumeric(TextBoxAmount, True))
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub DatePickerTransactionDate_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles DatePickerTransactionDate.SelectedDateChanged
        pageIsValid(DatePickerTransactionDate.Name, EntryValidation.ValidateDatePicker(DatePickerTransactionDate))
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub TextBoxComment_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBoxComment.TextChanged
        frmIsDirty = True
        setButtonProperties()
    End Sub
#End Region

#Region "Set Defaults"
    Sub LoadIncomeTypes()
        Dim IncomeTypes = From xList In IncomeDB.TransactionDescriptions _
                          Join tt In IncomeDB.TransactionTypes _
                          On xList.TransactionDescriptionID Equals tt.TransactionDescID _
                          Where tt.TransactionTypeDescID = 1 _
                          Select IncomeType = xList.TransactionDescription, IncomeTypeId = xList.TransactionDescriptionID _
                          Distinct

        ComboBoxIncomeType.ItemsSource = IncomeTypes
        ComboBoxIncomeType.DisplayMemberPath = "IncomeType"
        ComboBoxIncomeType.SelectedValuePath = "IncomeTypeId"
    End Sub

    Sub LoadSubHeader()

        If incomesList.Count > 1 Then
            ExpanderText.Text = incomesList.Count & " records found"
        Else
            ExpanderText.Text = incomesList.Count & " record found"
        End If

    End Sub

    Sub noSelectedData()
        listBoxIncome.SelectedIndex = -1
        frmIsDirty = False
        setButtonProperties()
        mainOverlay.Visibility = Visibility.Visible
    End Sub


    Sub setButtonProperties()
        If frmIsDirty Then
            RibbonButtonSave.IsEnabled = True
            RibbonButtonCancel.IsEnabled = True
            RibbonButtonDelete.IsEnabled = True
            'RibbonButtonNew.IsEnabled = False
        Else
            RibbonButtonSave.IsEnabled = False
            RibbonButtonCancel.IsEnabled = False
            RibbonButtonDelete.IsEnabled = False
            'RibbonButtonNew.IsEnabled = True
        End If
    End Sub

    Sub pageIsValid(ByVal sender As String, ByVal isValid As Boolean)
        Dim inArray As Boolean = False
        For i = 0 To al.Count - 1
            If al.Item(i) = sender Then
                If isValid Then
                    al.Remove(Trim(sender))
                End If
                inArray = True
                Exit For
            End If
        Next
        If Not inArray Then
            If Not isValid Then
                al.Add(Trim(sender))
            End If
        End If
        If al.Count > 0 Then
            _pageIsValid = False
        Else
            _pageIsValid = True
        End If
    End Sub
#End Region


End Class
